package com.qfedu.service.impl;

import cn.hutool.extra.mail.MailUtil;
import com.qfedu.dao.IUserDao;
import com.qfedu.dao.impl.UserDaoImpl;
import com.qfedu.entity.Result;
import com.qfedu.entity.User;
import com.qfedu.service.IUserService;

public class UserService implements IUserService {
    private IUserDao userDao = new UserDaoImpl();

    @Override
    public Result checkUser(String username, String password, String code,String codeNum) {

//        System.out.println(username);
//        System.out.println(password);
//        System.out.println(codeNum);
        if (!code.equals(codeNum)) {
            System.out.println("验证码错误");
            return new Result("验证码错误", false);
        } else {
            User user = userDao.checkUser(username, password);
            System.out.println(user);
            if (user == null) {
                return new Result("账户名或密码输入错误", false);
            } else if (user.getFlag() == 0) {
                return new Result("账户未激活", false);
            } else {
                return new Result("", true,user);
            }
        }
    }

    @Override
    public Result addUser(String username, String password, String email, String gender) {
        int code = (int) (Math.random() * 10000);
        int flag = 0;
        int i = userDao.addUser(username, password, email, gender, flag, code + "");
        if (i == 0) {
            return new Result("注册失败", false);
        } else {
            System.out.println(email);
            MailUtil.send(email, "小米商城用户激活", "欢迎注册小米商城:<a href='http://127.0.0.1:8080/xiaomi/active.jsp'>立即激活</a>  你的验证码是" + code, true);
            return new Result("注册成功", true);
        }
    }

    @Override
    public Result checkUserByName(String username) {
        User user = userDao.checkUserByName(username);
        if (user == null) {
            return new Result("用户名不存在，可以注册", true);
        } else {
            return new Result("用户名已存在", false);
        }
    }

    @Override
    public Result checkUserByEmail(String email) {
        User user = userDao.checkUserByEmail(email);
        if (user == null) {
            return new Result("邮箱不存在，可以注册", true);
        } else {
            return new Result("邮箱已存在", false);
        }
    }

    @Override
    public Result updateUserFlag(String code, String email) {
        int i = userDao.updateFlagByCode(code, email);
        if (i == 0) {
            return new Result("激活码输入错误", false);
        } else {
            return new Result("", true);
        }
    }
}
